<?php
class Silk_Mapi_OrderController extends Silk_Mapi_Controller_Action{
    public function IndexAction() {
        echo "OK";
    }

    public function cancelAction()
    {
    	$id = $this->getRequest()->getParam('id');
    	$_customer = $this->getCustomer();
    	$order = Mage::getModel('sales/order')->load($id);
    	if(!$order || !$order->getId())
    	{
    		$this->renderError("订单不存在！");
    		return;
    	}

    	if($order->getCustomerId() != $_customer->getId())
    	{
    		$this->renderError("无权访问！");
    		return;
    	}

        if(in_array($order->getStatus(), array('canceled','complete','closed')))
        {
            $this->renderError("已完成和已取消订单无法操作！");
            return;
        }

    	if($order->getStatus()!='pending' || !$order->canCancel())
    	{
            $rmas = Mage::getModel('zgb/rma')->getCollection()->addFieldToFilter('order_id', array('eq'=>$order->getId()));
            if($rmas->count())
            {
                $rma = $rmas->getFirstItem();
                if($rma->getStatus())
                {
                    $this->renderError("您的取消请求已处理，请等待客服确认！");
                    return;
                }
                else
                {
                    $this->renderError("您的请求已提交请等待处理！");
                    return;
                }
            }

    		//$this->renderError("订单正在处理中！请联系客服取消。");
            $rma = Mage::getModel('zgb/rma');
            $rma->setCustomerId($order->getCustomerId());
            $rma->setOrderId($order->getId());
            $rma->setIncrementId($order->getIncrementId());
            $rma->setCreatedAt(Mage::getSingleton('core/date')->gmtDate());
            $rma->save();
            $this->render(array(),"您的订单取消请求已记录，请等待处理！");
    		return;
    	}
        else
        {
    	   $order->cancel();
           $order->save();
           return $this->render(array(),"订单已取消！");
        }
    }
}